﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class InputHelper : MonoBehaviour, IControl<InputHelper> {
	// === Unity ======================================================================================================
	private void Update() {
		CheckClickedButton(new List<KeyCode> { KeyCode.A, KeyCode.LeftArrow }, Vector3.left);
		CheckClickedButton(new List<KeyCode> { KeyCode.D, KeyCode.RightArrow }, Vector3.right);
		if (SettingsGameModel.IsCamera2D) {
			CheckClickedButton(new List<KeyCode> { KeyCode.W, KeyCode.UpArrow }, Vector3.forward);
			CheckClickedButton(new List<KeyCode> { KeyCode.S, KeyCode.DownArrow }, Vector3.back);
		}

		if (_keyDownList.Count.Equals(0)) {
			return;
		}
		_ctrl.SetNextDirection(_keyDownList.Last());
	}

	// === Public =====================================================================================================
	#region IControl
	public InputHelper GetControl() {
		return this;
	}

	public void Initialize() {
		_ctrl = Controls.SnakeControl().GetControl();
	}

	public void Destroy() {
		Destroy(gameObject);
	}
	#endregion

	// === Private ====================================================================================================
	private SnakeCtrl _ctrl;
	private readonly List<Vector3> _keyDownList = new List<Vector3>();

	private void CheckClickedButton(IEnumerable<KeyCode> keyCodes, Vector3 direction) {
		if (keyCodes.Any(Input.GetKey)) {
			AddKeyToList(direction);
		} else {
			_keyDownList.Remove(direction);
		}
	}

	private void AddKeyToList(Vector3 direction) {
		if (_keyDownList.Contains(direction)) {
			return;
		}
		_keyDownList.Add(direction);
	}
}